package org.br.erp.base.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.br.erp.base.mapper.ErpBaseMapper;
import org.br.erp.base.service.IErpBaseService;
import org.br.erp.base.utils.ERPUtils;
import org.jeecg.modules.base.mapper.BaseCommonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ErpBaseServiceImpl implements IErpBaseService {

    @Autowired
    ErpBaseMapper erpBaseMapper;

    @Autowired
    BaseCommonMapper baseCommonMapper;

    public List<JSONObject> executeSql(String configig, Map queryMap){
        List<JSONObject> res=new ArrayList<>();
        String selecttablevalue = baseCommonMapper.selecttablevalue("onl_cgreport_head", "cgr_sql", "id", configig);
        //如果存在参数，则在这里进行拼接

        if(ERPUtils.ifHtppReqParamContainKey(queryMap,"fromitemid[]")){
            String[] httpReqParamsList = ERPUtils.getHttpReqParamsList(queryMap, "fromitemid[]");

            String insql = " ";
            for (String s : httpReqParamsList) {
                insql += "'" + s + "',";
            }

            insql = insql.substring(0, insql.length() - 1);

            if(selecttablevalue.indexOf("'#'")>=0){
                selecttablevalue = selecttablevalue.replaceAll("'#'", insql);
            }else {
                String join = String.join(",", httpReqParamsList);
                selecttablevalue = selecttablevalue + " where " + "item.fromitemid in (" + insql + ")";
            }
        }
        if(ERPUtils.ifHtppReqParamContainKey(queryMap,"fromitemid")){
            String fromitemid = ERPUtils.getHttpReqParam(queryMap, "fromitemid");
            if(selecttablevalue.indexOf("#")>=0) {
                selecttablevalue.replaceAll("#", fromitemid);
            }else {
                selecttablevalue = selecttablevalue + " where " + " item.fromitemid ='" + fromitemid + "'";
            }
        }

        List<Map<String, Object>> maps = SqlRunner.db().selectList(selecttablevalue);

        for (Map<String, Object> map : maps) {
            JSONObject jsonObject=new JSONObject(map);
            res.add(jsonObject);
        }

        return res;
    }


    @Override
    public List<JSONObject> executeSqlWithStr(String sqlstr){

        List<JSONObject> res=new ArrayList<>();

        List<Map<String, Object>> maps = SqlRunner.db().selectList(sqlstr);

        if(maps.size() == 0){
            return null;
        }
        for (Map<String, Object> map : maps) {
            if(map == null){
                return null;
            }
            JSONObject jsonObject=new JSONObject(map);
            res.add(jsonObject);
        }
        return res;
    }

    public List<JSONObject> executeSqlWithParams(Map queryMap ){
        List<JSONObject> res=new ArrayList<>();
        String querycode = queryMap.get("querycode").toString();
        String selectsql="select id,code,cgr_sql as sqlstr  from onl_cgreport_head where code='"+querycode+"'";
        List<Map<String, Object>> maps = SqlRunner.db().selectList(selectsql);
        if(maps.size() == 0){
            return res;
        }
        Map<String, Object> queryresMap = maps.get(0);

        String headid = queryresMap.get("id").toString();
        String sqlstr = queryresMap.get("sqlstr").toString();

        String paramsql="select param_name ,param_txt from onl_cgreport_param  where cgrhead_id ='"+headid+"'";
        List<Map<String, Object>> paramMaps = SqlRunner.db().selectList(paramsql);

        if(paramMaps.size()>0){
            String wheresql=" 1=1 and  ";
            for (Map<String, Object> paramMap : paramMaps) {
                if(paramMap.containsKey("param_txt")){
                    String param_txt = paramMap.get("param_txt").toString();
                    if(param_txt.equalsIgnoreCase("companyid")){
                        String param_name = paramMap.get("param_name").toString();
                        wheresql+= " and "+param_name+" = '"+ERPUtils.getCurCompanyid()+"'";
                    }
                    if(param_txt.equalsIgnoreCase("customerid") && queryMap.containsKey("customerid")){
                        String param_name = paramMap.get("param_name").toString();
                        wheresql+=" and "+param_name+" = '"+ queryMap.get("customerid").toString()+"'";
                    }
                    if(param_txt.equalsIgnoreCase("billdate") && queryMap.containsKey("billdate")){
                        String param_name = paramMap.get("param_name").toString();
                        wheresql+= " and "+ param_name +" <= '"+queryMap.get("billdate").toString()+"'";
                    }
                }
            }
            if(sqlstr.indexOf("where")>=0) {
                sqlstr = sqlstr +" and " + wheresql;
            }else {
                sqlstr = sqlstr + " where " + wheresql;
            }
        }

        List<Map<String, Object>> resuMap = SqlRunner.db().selectList(sqlstr);

        for (Map<String, Object> map : resuMap) {
            if(map !=null) {
                JSONObject jsonObject = new JSONObject(map);
                res.add(jsonObject);
            }
        }
        return res;

    }
    @Override
    @Transactional
    public void updateTableStatus(String tableName, String statusField, String statusValue, String idField, String idValue) {
         erpBaseMapper.updateTableStatus(tableName,statusField,statusValue,idField,idValue);
    }

    @Override
    @Transactional
    public void saveCustomFieldValues(Map<Object, Object> customFields, String tablename, String idvalue) {
        if(customFields!=null){
            for(Object key : customFields.keySet()){
                Object keyvalue = customFields.get(key);
                if(keyvalue!=null){
                    erpBaseMapper.updateTableStatus(tablename, (String) key, (String) keyvalue,"id",idvalue);
                }
            }
        }
    }

    @Override
    public void createTmpTable() {
        erpBaseMapper.createTmpTable();
       // erpBaseMapper.inserttotmptable(p);
    }

    @Override
    public void inserttotmptable(List<String> p) {
        erpBaseMapper.createTmpTable();
        erpBaseMapper.inserttotmptable(p);
    }
}
